package org.jeecg.modules.hc.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.hc.entity.HcCompanyMerchantSettlement;
import org.jeecg.modules.hc.entity.HcMerchant;
import org.jeecg.modules.hc.enums.HcMerchantSettlementTypeEnum;
import org.jeecg.modules.hc.service.IHcCompanyMerchantSettlementService;
import org.jeecg.modules.hc.service.IHcMerchantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 企业订餐商户结算
 * @Author: jeecg-boot
 * @Date:   2023-07-14
 * @Version: V1.0
 */
@Api(tags="企业订餐商户结算")
@RestController
@RequestMapping("/hc/hcCompanyMerchantSettlement")
@Slf4j
public class HcCompanyMerchantSettlementController extends JeecgController<HcCompanyMerchantSettlement, IHcCompanyMerchantSettlementService> {
	@Autowired
	private IHcCompanyMerchantSettlementService hcCompanyMerchantSettlementService;
	@Autowired
	private IHcMerchantService hcMerchantService;


	@ApiOperation("进行商家手动结算企业订单")
	@PostMapping(value = "/doSettlement")
	@Transactional
	public Result<?> doSettlement(@RequestBody List<HcCompanyMerchantSettlement> hcCompanyMerchantSettlementList){
		for (HcCompanyMerchantSettlement hcCompanyMerchantSettlement : hcCompanyMerchantSettlementList) {
			hcCompanyMerchantSettlementService.updateById(new HcCompanyMerchantSettlement()
					.setId(hcCompanyMerchantSettlement.getId())
					.setSettlementAmount(hcCompanyMerchantSettlement.getSettlementAmount())
					.setType(HcMerchantSettlementTypeEnum.SETTLED)
			);
		}
		return Result.OK("结算成功");
	}

	@ApiOperation("商户企业订单自动结算")
	@Transactional
	@PostMapping(value = "/doSettlementNew")
	public Result<?> doSettlementNew(@RequestBody List<HcCompanyMerchantSettlement> hcCompanyMerchantSettlementList) throws Exception {
		//商家批次单号 长度 1~32
		String outNo = UuidUtils.getUUID();
		//openId
		String openId = "";
		//备注
		String remarks = "";
		//转账总金额
		BigDecimal totalSettlementAmount = new BigDecimal(0);
		for (HcCompanyMerchantSettlement hcCompanyMerchantSettlement : hcCompanyMerchantSettlementList) {
			HcMerchant hcMerchant = hcMerchantService
					.getById(hcCompanyMerchantSettlementService
							.getById(hcCompanyMerchantSettlement.getId()).getMerchantId());
			if (hcMerchant.getStoreName().contains("•")){
				String storeName = hcMerchant.getStoreName().replace("•", "");
				remarks = storeName +":";
			}else {
				remarks = hcMerchant.getStoreName()+":";
			}
			totalSettlementAmount = totalSettlementAmount.add(hcCompanyMerchantSettlement.getSettlementAmount());
			openId = hcMerchant.getOpenId();
			hcCompanyMerchantSettlementService.updateById(new HcCompanyMerchantSettlement()
					.setId(hcCompanyMerchantSettlement.getId())
					.setSettlementAmount(hcCompanyMerchantSettlement.getSettlementAmount())
					.setOutNo(outNo)
					.setType(HcMerchantSettlementTypeEnum.SETTLING)
			);
		}
		//转账批次
		BigDecimal divide = totalSettlementAmount.divide(new BigDecimal(1999),0,BigDecimal.ROUND_UP);
		//超2000分批结算
		if (totalSettlementAmount.compareTo(new BigDecimal(2000)) == 1){
			int flag = 0;
			do {
				flag+=1;
				String remark = "";
				if (totalSettlementAmount.compareTo(new BigDecimal(1999)) == 1){
					//商家批次单号 长度 1~32
					String outNo1 = IdUtil.getSnowflake(0, 0).nextIdStr();
					// 转账备注
					remark = " 转账:1999元("+ flag+"/"+divide+")";
					hcMerchantService.transferToMerchant(openId, new BigDecimal(1999), outNo1,remarks +remark);
					totalSettlementAmount = totalSettlementAmount.subtract(new BigDecimal(1999));
				}else {
					// 转账备注
					remark = " 转账"+totalSettlementAmount+"元("+ flag+"/"+divide+")";
					hcMerchantService.transferToMerchant(openId, totalSettlementAmount, outNo,remarks + remark);
					totalSettlementAmount = totalSettlementAmount.subtract(new BigDecimal(1999));
				}
			}while (totalSettlementAmount.compareTo(new BigDecimal(0)) == 1);
		}else {
			//未超2000的直接结算
			remarks += totalSettlementAmount+"元";
			//转账给商户
			hcMerchantService.transferToMerchant(openId, totalSettlementAmount, outNo,remarks);
		}
		return Result.OK("结算已受理");
	}

	@ApiOperation("获取商家端-企业-数据-结算记录")
	@GetMapping(value = "/queryRecordListByLogin")
	public Result<List<HcCompanyMerchantSettlement>> queryRecordListByLogin(@RequestParam(name = "merchantId")String merchantId,
																	 @RequestParam(name = "companyId")String companyId) {
		List<HcCompanyMerchantSettlement> list = hcCompanyMerchantSettlementService.list(
				new LambdaQueryWrapper<HcCompanyMerchantSettlement>()
						.eq(HcCompanyMerchantSettlement::getMerchantId, merchantId)
						.eq(HcCompanyMerchantSettlement::getCompanyId,companyId)
						.eq(HcCompanyMerchantSettlement::getType, HcMerchantSettlementTypeEnum.SETTLED)
						.orderByDesc(HcCompanyMerchantSettlement::getSettlementDate)
		);
		return Result.OK(list);
	}

	@ApiOperation("获取商家端-企业-数据-收入总额")
	@GetMapping("/getMerchantDataTotalIncome")
	public Result<?> getMerchantDataTotalIncome(@RequestParam(name = "merchantId")String merchantId,
												@RequestParam(name = "companyId")String companyId) throws ParseException {
		HcMerchant hcMerchant = hcMerchantService.getById(merchantId);

		HcCompanyMerchantSettlement hcCompanyMerchantSettlement = hcCompanyMerchantSettlementService.getOne(new QueryWrapper<HcCompanyMerchantSettlement>()
				.select("ifnull(sum(if(TYPE in ('unsettled','settling','fail'), SETTLEMENT_AMOUNT, 0)), 0) as 'SETTLEMENT_AMOUNT'")
				.eq("MERCHANT_ID", merchantId).eq("COMPANY_ID",companyId));
		final BigDecimal[] settlementAmount = {hcCompanyMerchantSettlement.getSettlementAmount()};
		hcMerchant.setTotalIncome(settlementAmount[0]);
		return Result.ok(hcMerchant);
	}

	@GetMapping(value = "/queryRecordListByMerchantIdAndCompanyId")
	public Result<List<HcCompanyMerchantSettlement>> queryRecordListById(String merchantId,String companyId) {
		List<HcCompanyMerchantSettlement> list = hcCompanyMerchantSettlementService.list(
				new LambdaQueryWrapper<HcCompanyMerchantSettlement>()
						.eq(HcCompanyMerchantSettlement::getMerchantId, merchantId)
						.eq(HcCompanyMerchantSettlement::getCompanyId, companyId)
						.ne(HcCompanyMerchantSettlement::getType, HcMerchantSettlementTypeEnum.UNSETTLED)
						.orderByDesc(HcCompanyMerchantSettlement::getUpdateTime, HcCompanyMerchantSettlement::getSettlementDate)
		);
		return Result.OK(list);
	}



	 /**
	  * 企业订餐商户结算统计
	  * @return
	  */
	 @ApiOperation(value="企业订餐商户结算统计", notes="企业订餐商户结算统计")
	 @GetMapping(value = "/querySumByMerchantIdAndCompanyId")
	 public Result<?> getTotal(@RequestParam(name = "merchantId",required = false)String merchantId,
							   @RequestParam(name = "companyId",required = false)String companyId) {
		 Map<String, Object> map = hcCompanyMerchantSettlementService.getMap(new QueryWrapper<HcCompanyMerchantSettlement>()
				 .select("ifnull(sum(if(TYPE in ('unsettled','settling','fail'), SETTLEMENT_AMOUNT, 0)), 0) as 'all'")
				 .eq("MERCHANT_ID", merchantId).eq("COMPANY_ID",companyId)
		 );

		 JSONObject result = new JSONObject();
		 result.put("all", map.get("all"));
		 result.put("settled", map.get("settled"));
		 result.put("change", map.get("change"));
		 result.put("unsettled", map.get("unsettled"));
		 return Result.OK(result);
	 }

	 /**
	  * 后台结算列表
	  **/
	@ApiOperation(value="后台结算列表", notes="后台结算列表")
	@GetMapping(value = "/queryListByMerchantIdAndCompanyId")
	public Result<List<HcCompanyMerchantSettlement>> queryListById(String merchantId,String companyId) {
		List<HcCompanyMerchantSettlement> list = hcCompanyMerchantSettlementService.list(
				new LambdaQueryWrapper<HcCompanyMerchantSettlement>()
						.eq(HcCompanyMerchantSettlement::getMerchantId, merchantId)
						.eq(HcCompanyMerchantSettlement::getCompanyId, companyId)
						.in(HcCompanyMerchantSettlement::getType, Arrays.asList(HcMerchantSettlementTypeEnum.UNSETTLED
								, HcMerchantSettlementTypeEnum.SETTLING
								, HcMerchantSettlementTypeEnum.FAIL))
						.orderByDesc(HcCompanyMerchantSettlement::getSettlementDate)
		);
		return Result.OK(list);
	}

	/**
	 * 分页列表查询
	 *
	 * @param hcCompanyMerchantSettlement
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "企业订餐商户结算-分页列表查询")
	@ApiOperation(value="企业订餐商户结算-分页列表查询", notes="企业订餐商户结算-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<HcCompanyMerchantSettlement>> queryPageList(HcCompanyMerchantSettlement hcCompanyMerchantSettlement,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<HcCompanyMerchantSettlement> queryWrapper = QueryGenerator.initQueryWrapper(hcCompanyMerchantSettlement, req.getParameterMap());
		Page<HcCompanyMerchantSettlement> page = new Page<HcCompanyMerchantSettlement>(pageNo, pageSize);
		IPage<HcCompanyMerchantSettlement> pageList = hcCompanyMerchantSettlementService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param hcCompanyMerchantSettlement
	 * @return
	 */
	@ApiOperation(value="企业订餐商户结算-添加变动", notes="企业订餐商户结算-添加变动")
	@PostMapping(value = "/add")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> add(@RequestBody HcCompanyMerchantSettlement hcCompanyMerchantSettlement) {
		hcCompanyMerchantSettlement.setType(HcMerchantSettlementTypeEnum.CHANGE);
		hcCompanyMerchantSettlement.setUpdateTime(new Date());
		hcCompanyMerchantSettlementService.save(hcCompanyMerchantSettlement);
		String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		//找到当天的结算数据
		HcCompanyMerchantSettlement one = hcCompanyMerchantSettlementService.getOne(new LambdaQueryWrapper<HcCompanyMerchantSettlement>()
				.eq(HcCompanyMerchantSettlement::getCompanyId, hcCompanyMerchantSettlement.getCompanyId())
				.eq(HcCompanyMerchantSettlement::getMerchantId, hcCompanyMerchantSettlement.getMerchantId())
				.eq(HcCompanyMerchantSettlement::getType,HcMerchantSettlementTypeEnum.UNSETTLED)
				.eq(HcCompanyMerchantSettlement::getSettlementDate, today));
		if (null!= one){
			one.setSettlementAmount(one.getSettlementAmount().add(hcCompanyMerchantSettlement.getSettlementAmount()));
			hcCompanyMerchantSettlementService.updateById(one);
		}else {
			hcCompanyMerchantSettlement.setType(HcMerchantSettlementTypeEnum.UNSETTLED);
			hcCompanyMerchantSettlement.setId(UuidUtils.getUUID());
			hcCompanyMerchantSettlement.setSettlementDate(new Date());
			hcCompanyMerchantSettlementService.save(hcCompanyMerchantSettlement);
		}
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param hcCompanyMerchantSettlement
	 * @return
	 */
	@AutoLog(value = "企业订餐商户结算-编辑")
	@ApiOperation(value="企业订餐商户结算-编辑", notes="企业订餐商户结算-编辑")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_settlement:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody HcCompanyMerchantSettlement hcCompanyMerchantSettlement) {
		hcCompanyMerchantSettlementService.updateById(hcCompanyMerchantSettlement);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "企业订餐商户结算-通过id删除")
	@ApiOperation(value="企业订餐商户结算-通过id删除", notes="企业订餐商户结算-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_settlement:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		hcCompanyMerchantSettlementService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "企业订餐商户结算-批量删除")
	@ApiOperation(value="企业订餐商户结算-批量删除", notes="企业订餐商户结算-批量删除")
	//@RequiresPermissions("org.jeecg.modules:hc_company_merchant_settlement:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.hcCompanyMerchantSettlementService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "企业订餐商户结算-通过id查询")
	@ApiOperation(value="企业订餐商户结算-通过id查询", notes="企业订餐商户结算-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<HcCompanyMerchantSettlement> queryById(@RequestParam(name="id",required=true) String id) {
		HcCompanyMerchantSettlement hcCompanyMerchantSettlement = hcCompanyMerchantSettlementService.getById(id);
		if(hcCompanyMerchantSettlement==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(hcCompanyMerchantSettlement);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param hcCompanyMerchantSettlement
    */
    //@RequiresPermissions("org.jeecg.modules:hc_company_merchant_settlement:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HcCompanyMerchantSettlement hcCompanyMerchantSettlement) {
        return super.exportXls(request, hcCompanyMerchantSettlement, HcCompanyMerchantSettlement.class, "企业订餐商户结算");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("hc_company_merchant_settlement:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HcCompanyMerchantSettlement.class);
    }

}
